package com.my.ads.lib.live.service;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.my.ads.lib.AdSummary;
import com.my.ads.lib.utils.Utils;

/**
 * Created by xuanyang on 2018/3/23.
 */

public class LiveService extends Service {
    private final static int SERVICE_STA_ID = -0x1001;

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        if (Build.VERSION.SDK_INT < 25) {
            startService(new Intent(this, LiveInnerService.class));
            startForeground(SERVICE_STA_ID, new Notification());
        }

        try {
            Utils.initLockScreenReceiver(getApplicationContext());
            Utils.initWeatherReceiver(getApplicationContext());
            Utils.initPowerInfoReceiver(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            AdSummary.getInstance().cacheAllAd(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //守护 Service 组件的启用状态, 使其不被 MAT 等工具禁用
        try {
            getPackageManager().setComponentEnabledSetting(new ComponentName(getPackageName(), LiveService.class.getName()),
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        } catch (Exception e) {
        }

        return START_STICKY;


    }

    public static class LiveInnerService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(SERVICE_STA_ID, new Notification());
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            throw new UnsupportedOperationException("Not yet implemented");
        }


    }
}
